package com.leetcode.LeetCode精选TOP面试题;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author 覃国强
 * @date 2022-07-01 16:09
 */
public class 题库_0150_逆波兰表达式求值 {

  static
  class Solution {
    public int evalRPN(String[] tokens) {
      if (tokens == null || tokens.length == 0) {
        return 0;
      }
      Deque<Integer> stack = new ArrayDeque<>();
      for (String token : tokens) {
        if (token.length() > 1 || Character.isDigit(token.charAt(0))) {
          stack.push(Integer.parseInt(token));
        } else {
          int second = stack.pop();
          int first = stack.pop();
          int answer = calculate(first, second, token);
          stack.push(answer);
        }
      }
      return stack.pop();
    }

    private int calculate(int first, int second, String token) {
      switch (token) {
        case "+":
          return first + second;
        case "-":
          return first - second;
        case "*":
          return first * second;
        default:
          return first / second;
      }
    }
  }

}
